package console;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.text.MaskFormatter;

import main.ProcesProcessor;

public class LeftPanel extends JPanel {

	/** serialization uid */
	private static final long serialVersionUID = 5645061102988184538L;

	private RightPanel rightPanel = null;
	private static final String numbers = "0123456789\b";
	private Box horizontalBox1;
	private Box horizontalBox2;
	private Box horizontalBox3;
	private Box verticalBox1;
	private Box verticalBox2;

	private List<Container> listaWartosci = null;

	private int dlugoscProcesow = 100;

	public LeftPanel(final RightPanel rp) {
		createContainerList();
		this.rightPanel = rp;
		Border border = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
		this.setBorder(border);
		this.setLayout(new FlowLayout());

		verticalBox1 = Box.createVerticalBox();
		verticalBox2 = Box.createVerticalBox();
		this.add(verticalBox1);

		horizontalBox1 = Box.createHorizontalBox();
		horizontalBox2 = Box.createHorizontalBox();
		horizontalBox3 = Box.createHorizontalBox();

		verticalBox1.add(horizontalBox1);
		Box boxH = Box.createHorizontalBox();
		JLabel jl = new JLabel("Podaj dlugość symulacji: ");
		final JTextField txtF2 = new JTextField();
		boxH.add(jl);
		boxH.add(txtF2);
		verticalBox1.add(boxH);
		verticalBox1.add(horizontalBox2);
		verticalBox1.add(verticalBox2);
		verticalBox1.add(horizontalBox3);

		JLabel processesLabel = new JLabel("Ilość procesów: ");

		final JFormattedTextField txtF1 = new JFormattedTextField(
				createFormatter("#"));
		txtF1.setPreferredSize(new Dimension(50, (int) txtF1.getSize()
				.getHeight()));
		JButton zatwierdz = new JButton("Zatwierdz procesy");

		zatwierdz.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (txtF1.getValue() == null || "".equals(txtF1.getValue())) {
					return;
				}
				ustawWartosci(Integer.parseInt(txtF1.getValue().toString()));
			}
		});

		horizontalBox1.add(processesLabel);
		horizontalBox1.add(txtF1);

		horizontalBox2.add(zatwierdz);

		JButton czyscZawartosc = new JButton("Przeczysc dane");
		czyscZawartosc.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				txtF1.setValue("");
				czyscDane();

			}
		});

		horizontalBox3.add(czyscZawartosc);

		JButton start = new JButton("Wystartuj");
		horizontalBox3.add(start);
		start.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (txtF1.getValue() == null || "".equals(txtF1.getValue())) {
					JOptionPane.showMessageDialog(null,
							"Proszę podac ilośc procesów!");
					return;
				}
				if (txtF2.getText() == null || "".equals(txtF2.getText())) {
					JOptionPane.showMessageDialog(null,
							"Proszę podac długość symulacji!");
					return;
				} else {
					dlugoscProcesow = Integer.parseInt(txtF2.getText()
							.toString());
				}
				if(!txtF2.getText().matches("[0-9]{1,3}")){
					JOptionPane.showMessageDialog(null,
							"Długość symulacji musi byc liczbą z zakresu od 1 do 999");
					return;
				}
				int iloscProcesow = Integer.parseInt((String) txtF1.getValue());
				ProcesProcessor processor = new ProcesProcessor(new Double(
						dlugoscProcesow));
				if (iloscProcesow == 0) {
					return;
				}
				rp.clearAxises();
				// wstepna walidacja
				for (int i = 0; i < iloscProcesow; i++) {
					if (listaWartosci.get(i).getTx1().getText() == null
							|| "".equals(listaWartosci.get(i).getTx1()
									.getText())) {
						JOptionPane.showMessageDialog(null,
								"Prosze podac wszystkie dane!");
						return;
					}

					if (listaWartosci.get(i).getTx2().getText() == null
							|| "".equals(listaWartosci.get(i).getTx2()
									.getText())) {
						JOptionPane.showMessageDialog(null,
								"Prosze podac wszystkie dane!");
						return;
					}
					
					if(!listaWartosci.get(i).getTx2().getText().matches("[0-9]{1,3}")
							|| !listaWartosci.get(i).getTx2()
									.getText().matches("[0-9]{1,3}")){
						JOptionPane.showMessageDialog(null,
								"Prosze podać tylko liczby z maxymalnie trzema cyframi!");
						return;
					}
				}

				for (int i = 0; i < iloscProcesow; i++) {
					processor.dodajProces(new Double((String) listaWartosci
							.get(i).getTx1().getText()), new Double(
							(String) listaWartosci.get(i).getTx2().getText()));
				}
				int[][] rmsTab;
				int[][] edfTab;
				processor.ustawPiorytety();
				processor.symulacjaRMS();
				rmsTab = processor.getProcessesStates();
				processor.clearHistory();
				processor.symulacjaEDF();
				edfTab = processor.getProcessesStates();
				processor.clearHistory();
				processor.clearId();
				rp.paintGanttDiagram(rmsTab, edfTab, dlugoscProcesow,
						iloscProcesow);

			}
		});

	}

	private void ustawWartosci(int ilosc) {
		verticalBox2.removeAll();
		for (int i = 0; i < ilosc; i++) {
			Container c = listaWartosci.get(i);
			verticalBox2.add(c.getBox());
		}
		this.updateUI();
	}

	private void czyscDane() {
		for (Container c : listaWartosci) {
			c.getTx1().setText("");
			c.getTx2().setText("");
		}
	}

	private void createContainerList() {
		listaWartosci = new ArrayList<Container>();
		for (int i = 0; i < 9; i++) {
			Container c = new Container("Długość prc nr." + (i + 1) + ": ",
					"Okres: ");
			listaWartosci.add(c);

		}
	}

	protected MaskFormatter createFormatter(String s) {
		MaskFormatter formatter = null;
		try {
			formatter = new MaskFormatter(s);
		} catch (java.text.ParseException exc) {
			System.err.println("formatter is bad: " + exc.getMessage());
			// System.exit(-1);
		}
		return formatter;
	}

}
